import hx.assets.Assets;
import haxe.io.Path;
import hx.display.BitmapData;
import hx.assets.BitmapDataFuture;
import hx.assets.JsonFuture;
import hx.assets.Future;

class MovieClipJsonLoader extends Future<JsonAtlas, String> {
	override function post() {
		super.post();
		// 开始加载逻辑
		new JsonFuture(this.getLoadData()).onComplete((json:MovieClipJsonLoaderData) -> {
			// 解析读取到图片路径
			var assets = new Assets();
			for (image in json.images) {
				var bitmapDataPath = image;
				bitmapDataPath = Path.join([Path.directory(this.getLoadData()), bitmapDataPath]);
				assets.loadBitmapData(bitmapDataPath);
			}
			assets.onComplete((a) -> {
				this.completeValue(new JsonAtlas(a, json));
			});
			assets.onError(this.errorValue);
			assets.start();
		}).onError(this.errorValue);
	}
}

typedef MovieClipJsonLoaderData = {
	var framerate:Int;
	var images:Array<String>;
	var frames:Array<Array<Float>>;
	var animations:AnimateData;
}

enum abstract AnimateData(Dynamic) {
	/**
	 * 获得帧数据
	 */
	public var frames(get, never):Array<Int>;

	private function get_frames():Array<Int> {
		if (this is Int) {
			return [this];
		} else if (this is Array) {
			var start = this[0];
			var end = this[1];
			var arr = [];
			while (start <= end) {
				arr.push(start);
				start++;
			}
			return arr;
		} else {
			return this.frames;
		}
	}

	/**
	 * 速度
	 */
	public var speed(get, never):Int;

	private function get_speed():Int {
		if (this is Int) {
			return 1;
		} else if (this is Array) {
			return this[2];
		} else {
			return this.speed;
		}
	}
}
